from openpyxl import Workbook 
from openpyxl import load_workbook
import os
import shutil
import json

def get_bili_cfg():
    json_file = "cfg.json"
    with open(json_file) as f:
        cfg = json.load(f)
    return cfg

def get_wb(path):
    filelist = os.listdir(path)
    wb = None
    for filename in filelist:
        if filename.endswith(".xlsx"):
            wb = load_workbook(path + "/" + filename)
    return wb

def make_block(block_idx, src_ws, item_per_block, start_row):
    block_path = "blocks/block" + str(block_idx)
    # 删除已经存在的内容
    if os.path.exists(block_path):
        shutil.rmtree(block_path)

    # 重新生成目录
    os.makedirs(block_path + "/targets")

    # 创建工作簿
    wb = Workbook()
    ws = wb.active

    # 复制标题
    for col in range(1, src_ws.max_column + 1):
        ws.cell(1, col).value = src_ws.cell(1, col).value

    # 复制数据
    for item_idx in range(0, item_per_block):
        for col in range(1, src_ws.max_column + 1):
            ws.cell(2 + item_idx, col).value = src_ws.cell(start_row, col).value
        start_row += 1

    # 保存文件
    wb.save(block_path + "/targets/test.xlsx")
    return start_row

def main():    
    path = "rawdata"
    
    cfg = get_bili_cfg()

    blocks = cfg["blocks"]

    wb = get_wb(path)
    if wb == None:
        print("[ERR ] 没有可用的原始数据！")
        return

    ws = wb.active

    max_row = ws.max_row
    max_cloumn = ws.max_column

    print("行：", max_row)
    print("列：", max_cloumn)
    
    # 跳过标题
    start_row = 2
    max_row -= 1
    
    item_per_block = int(max_row / blocks)
    
    mod = max_row % blocks
    if mod != 0:
        blocks += 1
        print("有个小块项目数：", mod)

    print("块数：", blocks)
    print("每块项目数：", item_per_block)
    
    # 删除已经存在的视频
    if os.path.exists("blocks"):
        shutil.rmtree("blocks")
    
    os.mkdir("blocks")

    # 生成所有块
    for block_idx in range(0, blocks):
        if block_idx == blocks - 1 and mod != 0: # 最后一个块就是存放剩余的数量的内容
            start_row = make_block(block_idx, ws, mod, start_row)
        else:
            start_row = make_block(block_idx, ws, item_per_block, start_row)
        
    print("[INFO] 生成所有块成功！")

if __name__ == '__main__':
    main()
